from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QTableWidget, QHBoxLayout,
    QPushButton, QTableWidgetItem, QHeaderView, QComboBox,
    QLineEdit, QToolBar,  QSplitter
)
from PyQt6.QtGui import QIcon,QAction
from PyQt6.QtCore import Qt

class TableDesigner(QWidget):
    def __init__(self, table_info, parent=None):
        super().__init__(parent)
        self.table_info = table_info

        # 创建布局
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        # 创建工具栏
        self.create_toolbar()
        layout.addWidget(self.toolbar)

        # 创建分割器
        splitter = QSplitter(Qt.Orientation.Vertical)
        layout.addWidget(splitter)

        # 表结构设计器
        self.designer_table = QTableWidget()
        self.designer_table.setColumnCount(6)
        self.designer_table.setHorizontalHeaderLabels(["列名", "数据类型", "长度", "主键", "非空", "默认值"])
        self.designer_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Interactive)
        self.designer_table.horizontalHeader().setStretchLastSection(True)
        splitter.addWidget(self.designer_table)

        # SQL预览
        self.sql_preview = QTextEdit()
        self.sql_preview.setReadOnly(True)
        splitter.addWidget(self.sql_preview)

        splitter.setSizes([400, 200])

        # 加载表结构
        self.load_table_structure()

    def create_toolbar(self):
        self.toolbar = QToolBar("表设计工具栏")
        self.toolbar.setIconSize(QSize(20, 20))

        # 保存按钮
        save_action = QAction(QIcon("resources/icons/save.png"), "保存更改", self)
        save_action.triggered.connect(self.save_changes)
        self.toolbar.addAction(save_action)

        # 新增列按钮
        add_column_action = QAction(QIcon("resources/icons/add_column.png"), "新增列", self)
        add_column_action.triggered.connect(self.add_column)
        self.toolbar.addAction(add_column_action)

        # 删除列按钮
        delete_column_action = QAction(QIcon("resources/icons/delete_column.png"), "删除列", self)
        delete_column_action.triggered.connect(self.delete_column)
        self.toolbar.addAction(delete_column_action)

        self.toolbar.addSeparator()

        # 生成SQL按钮
        generate_sql_action = QAction(QIcon("resources/icons/generate_sql.png"), "生成SQL", self)
        generate_sql_action.triggered.connect(self.generate_sql)
        self.toolbar.addAction(generate_sql_action)

    def load_table_structure(self):
        """加载表结构"""
        # 在实际应用中，从数据库获取表结构
        # 这里使用模拟数据
        columns = [
            ["id", "int", None, True, True, "AUTO_INCREMENT"],
            ["name", "varchar", 255, False, True, ""],
            ["email", "varchar", 255, False, False, ""],
            ["created_at", "datetime", None, False, True, "CURRENT_TIMESTAMP"]
        ]

        self.designer_table.setRowCount(len(columns))

        for row_idx, col in enumerate(columns):
            # 列名
            name_item = QTableWidgetItem(col[0])
            self.designer_table.setItem(row_idx, 0, name_item)

            # 数据类型
            type_combo = QComboBox()
            type_combo.addItems(["int", "varchar", "text", "datetime", "float", "boolean"])
            type_combo.setCurrentText(col[1])
            self.designer_table.setCellWidget(row_idx, 1, type_combo)

            # 长度
            length_edit = QLineEdit(str(col[2]) if col[2] else "")
            self.designer_table.setCellWidget(row_idx, 2, length_edit)

            # 主键
            pk_check = QCheckBox()
            pk_check.setChecked(col[3])
            pk_check.setStyleSheet("margin-left:50%; margin-right:50%;")
            self.designer_table.setCellWidget(row_idx, 3, pk_check)

            # 非空
            not_null_check = QCheckBox()
            not_null_check.setChecked(col[4])
            not_null_check.setStyleSheet("margin-left:50%; margin-right:50%;")
            self.designer_table.setCellWidget(row_idx, 4, not_null_check)

            # 默认值
            default_edit = QLineEdit(col[5])
            self.designer_table.setItem(row_idx, 5, default_edit)

    def add_column(self):
        """添加新列"""
        row_count = self.designer_table.rowCount()
        self.designer_table.insertRow(row_count)

        # 设置默认值
        name_item = QTableWidgetItem("new_column")
        self.designer_table.setItem(row_count, 0, name_item)

        type_combo = QComboBox()
        type_combo.addItems(["int", "varchar", "text", "datetime", "float", "boolean"])
        type_combo.setCurrentText("varchar")
        self.designer_table.setCellWidget(row_count, 1, type_combo)

        length_edit = QLineEdit("255")
        self.designer_table.setCellWidget(row_count, 2, length_edit)

        pk_check = QCheckBox()
        pk_check.setStyleSheet("margin-left:50%; margin-right:50%;")
        self.designer_table.setCellWidget(row_count, 3, pk_check)

        not_null_check = QCheckBox()
        not_null_check.setChecked(True)
        not_null_check.setStyleSheet("margin-left:50%; margin-right:50%;")
        self.designer_table.setCellWidget(row_count, 4, not_null_check)

        default_edit = QLineEdit()
        self.designer_table.setItem(row_count, 5, default_edit)

    def delete_column(self):
        """删除选中的列"""
        selected_rows = set()
        for item in self.designer_table.selectedItems():
            selected_rows.add(item.row())

        # 从后往前删除
        for row in sorted(selected_rows, reverse=True):
            self.designer_table.removeRow(row)

    def generate_sql(self):
        """生成SQL语句"""
        sql = f"ALTER TABLE {self.table_info['name']}\n"

        changes = []
        for row in range(self.designer_table.rowCount()):
            col_name = self.designer_table.item(row, 0).text()
            col_type = self.designer_table.cellWidget(row, 1).currentText()
            col_length = self.designer_table.cellWidget(row, 2).text()
            is_pk = self.designer_table.cellWidget(row, 3).isChecked()
            not_null = self.designer_table.cellWidget(row, 4).isChecked()
            default = self.designer_table.item(row, 5).text()

            # 构建类型
            type_str = col_type
            if col_length and col_type in ["varchar", "char"]:
                type_str += f"({col_length})"

            # 构建列定义
            col_def = f"{col_name} {type_str}"

            if not_null:
                col_def += " NOT NULL"

            if default:
                col_def += f" DEFAULT '{default}'"

            if is_pk:
                col_def += " PRIMARY KEY"

            changes.append(f"MODIFY COLUMN {col_def}")

        sql += ",\n".join(changes) + ";"
        self.sql_preview.setText(sql)

    def save_changes(self):
        """保存更改到数据库"""
        # 在实际应用中，执行生成的SQL
        sql = self.sql_preview.toPlainText()
        if not sql:
            return

        # 执行SQL
        # ...
        QMessageBox.information(self, "保存成功", "表结构已更新")